package org.huaxi.spring.aop;

import org.huaxi.spring.support.SpringDSConfigurationExtractor;
import org.springframework.aop.Advisor;
import org.springframework.aop.framework.autoproxy.AbstractBeanFactoryAwareAdvisingPostProcessor;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.util.StringValueResolver;

/**
 * e
 * Created by huwei on 2019/5/10.
 */
public class DynamicDSAopBeanPostProcessor extends AbstractBeanFactoryAwareAdvisingPostProcessor implements BeanPostProcessor, EmbeddedValueResolverAware {

  private StringValueResolver embeddedValueResolver;

  @Override
  public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    return bean;
  }

  @Override
  public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    this.advisor = getAdvisor();
    return super.postProcessAfterInitialization(bean,beanName);
  }

  @Override
  public void setEmbeddedValueResolver(StringValueResolver resolver) {
    this.embeddedValueResolver = resolver;
  }

  private Advisor getAdvisor() {
    return new DynamicDSSwitchingAdvisor(new SpringDSConfigurationExtractor(embeddedValueResolver));
  }
}
